class_name CursorSystem
extends BaseSystem

#region 属性
@export var default_cursor_infos:Array[CursorInfo]
var default_cursor_dict:Dictionary = {}
var cursor_dict:Dictionary = {}
var connect_obj:ConnectObj
var cursor_node_dict:Dictionary = {}
var cur_cursor:Cursor
var locking:bool
#endregion
#region 字段
#endregion
#region 信号
#endregion

#region 基类方法
func init_system(args = null):
	super(args)
	for info in default_cursor_infos:
		if not default_cursor_dict.has(info.game_state):
			default_cursor_dict[info.game_state] = info
		if not cursor_dict.has(info.game_state):
			cursor_dict[info.game_state] = info
	connect_obj = ConnectObj.new(GameManager.game_state_changed,[_on_game_state_changed])
	_on_game_state_changed(GameManager.get_cur_game_state())
#endregion
#region 公共方法
## 动态设置CursorInfo
func set_cursor_info(game_state:GameEnum.GameState,cursor_info:CursorInfo = null):
	if cursor_info or default_cursor_dict.has(game_state):
		cursor_dict.set(game_state,cursor_info if cursor_info else default_cursor_dict.get(game_state))
	if cursor_node_dict.has(game_state):
		cursor_node_dict[game_state].queue_free()
		cursor_node_dict[game_state] = null
	_force_update()
#endregion
#region 私有方法
func _set_mouse_mode(is_show:bool):
	Input.mouse_mode = Input.MOUSE_MODE_VISIBLE if is_show else Input.MOUSE_MODE_HIDDEN
func _lock_mouse(lock:bool):
	locking = lock
func _set_cursor_enable(cursor:Cursor,enable:bool):
	cursor.set_enable(enable)
func _get_cursor_node(game_state:GameEnum.GameState) -> Cursor:
	if not cursor_node_dict.has(game_state):
		if cursor_dict.has(game_state):
			var cursor = cursor_dict[game_state].cursor_scene.instantiate()
			cursor_node_dict[game_state] = cursor
			cursor.init()
			%CursorCanvasLayer.add_child(cursor)
			return cursor
		else:
			return null
	return cursor_node_dict[game_state]
func _on_game_state_changed(cur_game_state:GameEnum.GameState):
	if cur_cursor:
		_set_cursor_enable(cur_cursor,false)
	cur_cursor = _get_cursor_node(cur_game_state)
	if cur_cursor:
		_set_mouse_mode(false)
		_set_cursor_enable(cur_cursor,true)
		_lock_mouse(true)
	else:
		_set_mouse_mode(true)
		_lock_mouse(false)
func _force_update():
	if cur_cursor:
		_set_cursor_enable(cur_cursor,false)
	cur_cursor = _get_cursor_node(GameManager.get_cur_game_state())
	if cur_cursor:
		_set_mouse_mode(false)
		_set_cursor_enable(cur_cursor,true)
		_lock_mouse(true)
	else:
		_set_mouse_mode(true)
		_lock_mouse(false)
#endregion
#region 生命周期函数
func _process(delta: float) -> void:
	if locking and cur_cursor:
		cur_cursor.global_position = cur_cursor.get_global_mouse_position()
func _exit_tree() -> void:
	for cursor in cursor_node_dict.values():
		cursor.queue_free()
	cursor_node_dict.clear()
	if connect_obj:
		connect_obj.disconnect_all()
#endregion
